use anyhow::{Result, anyhow};

/// 音频数据转换工具，负责按不同位深和类型解析采样值
pub fn convert_to_sample(
    buffer: &[u8],
    position: usize,
    symbol_type: &str,
    depth: u32,
) -> Result<f32> {
    let bytes_per_sample = (depth / 8) as usize;
    if position + bytes_per_sample > buffer.len() {
        return Err(anyhow!(
            "样本读取越界: pos={}, depth={}, buffer_len={}",
            position,
            depth,
            buffer.len()
        ));
    }

    match (symbol_type, depth) {
        ("float", 32) => {
            let slice: [u8; 4] = buffer[position..position + 4]
                .try_into()
                .map_err(|_| anyhow!("解析 float32 失败"))?;
            Ok(f32::from_le_bytes(slice))
        }
        ("int", 16) => {
            let slice: [u8; 2] = buffer[position..position + 2]
                .try_into()
                .map_err(|_| anyhow!("解析 int16 失败"))?;
            Ok(i16::from_le_bytes(slice) as f32)
        }
        ("int", 24) => Ok(convert_int24(&buffer[position..position + 3]) as f32),
        ("int", 32) => {
            let slice: [u8; 4] = buffer[position..position + 4]
                .try_into()
                .map_err(|_| anyhow!("解析 int32 失败"))?;
            Ok(i32::from_le_bytes(slice) as f32)
        }
        _ => Err(anyhow!(
            "不支持的 symbolType/depth 组合: {}-{}",
            symbol_type,
            depth
        )),
    }
}

/// 针对 24 位整数的解析逻辑（小端序，带符号扩展）
fn convert_int24(bytes: &[u8]) -> i32 {
    let value = (bytes[0] as i32) | ((bytes[1] as i32) << 8) | ((bytes[2] as i32) << 16);
    if (value & 0x0080_0000) != 0 {
        value | (0xFF00_0000u32 as i32)
    } else {
        value
    }
}
